package com.example.demo;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class Controller {
    @Resource
    Repo repo;

    @GetMapping("/get")
    public Page<LoveEvent> get(@RequestParam("page") int page, @RequestParam("size") int size) {
        return repo.findAll(PageRequest.of(page, size, Sort.Direction.DESC, "id"));
    }

    @GetMapping("/delete")
    public int delete (@RequestParam("id")int id){
        try {
            repo.deleteById(id);
        }catch (Exception e){
            System.out.println(e);
            return 1;
        }
        return 0;
    }
    @PostMapping("/update")
    public int update(@RequestParam("id")int id,
                      @RequestParam("content")String content,
                      @RequestParam("note")String note,
                      @RequestParam("completed")int completed){
        try {
            LoveEvent event = new LoveEvent();
            event.completed = completed;
            event.content = content;
            event.note = note;
            event.date = String.valueOf(System.currentTimeMillis());
            event.id = id;
            repo.save(event);
        }catch (Exception e){
            return 1;
        }
        return 0;
    }

    @PostMapping("/save")
    public int save(@RequestParam(value = "content",defaultValue = "") String content,
                    @RequestParam(value = "note",defaultValue = "") String note,
                    @RequestParam(value = "completed",defaultValue = "0") int completed
    ){
        LoveEvent event = new LoveEvent();
        event.completed = completed;
        event.content = content;
        event.note = note;
        event.date = String.valueOf(System.currentTimeMillis());
        try {
            event.id = repo.getMaxId()+1;
        }catch (Exception e){
            event.id = 1;
        }
        try {
            repo.save(event);
        }catch (Exception e){
            return 1;
        }
        return 0;
    }
}
